package edu.uob;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class DropAttribute {
    public static String drop(String tableName, String attributeName) {
        Path path = getTablePath(tableName);
        if (Files.exists(path)) {
            try {
                List<String> lines = Files.readAllLines(path);
                if (!lines.isEmpty()) {
                    String firstLine = lines.get(0);
                    if (firstLine.contains(attributeName)) {
                        // 更新第一行，移除属性名
                        String[] attributes = firstLine.split("\\s+");
                        StringBuilder updatedFirstLine = new StringBuilder();
                        for (String attr : attributes) {
                            if (!attr.equals(attributeName)) {
                                updatedFirstLine.append(attr).append(" ");
                            }
                        }
                        lines.set(0, updatedFirstLine.toString().trim());

                        // 删除属性对应的列
                        for (int i = 1; i < lines.size(); i++) {
                            String[] values = lines.get(i).split("\\s+");
                            StringBuilder updatedLine = new StringBuilder();
                            for (int j = 0; j < attributes.length; j++) {
                                if (!attributes[j].equals(attributeName)) {
                                    updatedLine.append(values[j]).append(" ");
                                }
                            }
                            lines.set(i, updatedLine.toString().trim());
                        }

                        // 将更新后的内容写回文件
                        Files.write(path, lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
                        return "[OK]";
                    } else {
                        return "[ERROR]: Attribute '" + attributeName + "' does not exist.";
                    }
                } else {
                    return "[ERROR]: The file is empty.";
                }
            } catch (IOException e) {
                return "[ERROR]: Failed to read/write the file: " + e.getMessage();
            }
        } else {
            return "[ERROR]: Table does not exist.";
        }
    }

    private static Path getTablePath(String tableName) {
        String file_name = "." + File.separator + "databases" + File.separator + CmdType.getDbName() + File.separator + tableName + ".tab";
        return Path.of(file_name);
    }
}
